//
//  Test1ViewController.swift
//  JKRegex
//
//  Created by 王冲 on 2018/1/30.
//  Copyright © 2018年 希爱欧科技有限公司. All rights reserved.
//

import UIKit

class Test1ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        
        // 1.添加label
        view.addSubview(label)
        
        // 2.字符串
        let str = "Hello, my name is Ben. Please visit my ben website at https://www.forta.com/."
        // 3.获取满足搜索添加的区域
        let range : [NSRange] = textRegex(str: str)
        // 根据区域展示label
        label.attributedText = attribute(range1:range , str: str, font: 22)
    }
    
    
    func attribute(range1: [NSRange],str: String,font: CGFloat) -> NSMutableAttributedString {
        
        //富文本设置
        let attributeString = NSMutableAttributedString(string:str)
        
        for range in range1 {
            
            //从文本0开始6个字符字体HelveticaNeue-Bold,16号
            attributeString.addAttribute(NSAttributedStringKey.font, value: UIFont(name: "HelveticaNeue-Bold", size: font)!,range: range)
            //设置字体颜色
            attributeString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.blue,range: range)
            //设置文字背景颜色
            attributeString.addAttribute(NSAttributedStringKey.backgroundColor, value: UIColor.green,range: range)
        }
    
        return attributeString
        
    }
    
    // 1.匹配纯文本
    func textRegex(str: String) -> [NSRange]{
        
        var array : [NSRange] = [NSRange]()
        do {
            // 1.1.定义规则
            let pattern = "ben"
            // 1.2.创建正则表达式对象
            let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
            // 1.3.开始匹配
            // matches 匹配字符串中所有的符合规则的字符串
            let res = regex.matches(in: str, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, str.count))
            
            for checkingRes in res
            {
                // 符合规定规则的字符串的范围
                print("range\(checkingRes.range)")
                // substring 符合规定规则的字符串
                print((str as NSString).substring(with: checkingRes.range))
                array.append(checkingRes.range)
            }
            
            return array
            
        } catch {
            
            print(error)
        }
        
        return array
    }
    
    // 展示的label
    lazy var label: UILabel = {
        
        let label1: UILabel = UILabel(frame: CGRect(x: 16, y: 0, width: UIScreen.main.bounds.size.width-32, height: UIScreen.main.bounds.size.height))
        label1.font = UIFont.systemFont(ofSize: 22)
        label1.numberOfLines = 0
        label1.backgroundColor = UIColor.white

        return label1
    }()


}
